package com.tsinkai.ettp.practice;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

public class HMacPra {
	
	public static String src = "hello world";
	
	public static void main(String[] args) {
		jdkHMacMD5();
		bcHMacMD5();
	}
	
	public static void jdkHMacMD5() {
		try {
			//获得jdk默认实现的秘钥
			KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] key = secretKey.getEncoded();
			//可以自定义生成,必须是偶数位
//			byte[] key = Hex.decodeHex(new char[] {'a','a','a','a','a','a','a','a'});
			
			
			SecretKey restreSecretKey = new SecretKeySpec(key, "HmacMD5");//该步骤是为了生成一个符合HMacMD5的秘钥
			Mac mac = Mac.getInstance(restreSecretKey.getAlgorithm());
			mac.init(restreSecretKey);
			byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());
			System.out.println("jdk hmacMD5:"+Hex.encodeHexString(hmacMD5Bytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void bcHMacMD5() {
		HMac hmac = new HMac(new MD5Digest());
		hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("123456")));
		hmac.update(src.getBytes(),0,src.getBytes().length);
		
		byte[] hMacMD5bytes = new byte[hmac.getMacSize()];
		hmac.doFinal(hMacMD5bytes, 0);
		
		System.out.println("bc hmacMD5:" + Hex.encodeHexString(hMacMD5bytes));
	}
}
